// 案例数据
const cases = [
    {
        id: 1,
        title: '某大型制造企业债券融资案例',
        category: '债券融资',
        image: '/images/case1.jpg',
        description: '为客户设计并发行30亿元公司债券，优化融资结构，降低融资成本。',
        results: ['成功发行30亿元公司债券', '融资成本降低2.5%', '债项评级AA+']
    },
    {
        id: 2,
        title: '某科技公司租赁保理方案',
        category: '租赁保理',
        image: '/images/case2.jpg',
        description: '为客户提供设备租赁及应收账款保理服务，解决资金周转难题。',
        results: ['租赁融资1.5亿元', '保理规模5000万元', '缓解资金压力']
    },
    {
        id: 3,
        title: '某集团企业金融顾问服务',
        category: '金融顾问',
        image: '/images/case3.jpg',
        description: '为客户提供全方位金融顾问服务，优化资本结构，提升企业价值。',
        results: ['制定融资战略', '优化资本结构', '估值提升30%']
    },
    {
        id: 4,
        title: '某商贸企业供应链金融方案',
        category: '租赁保理',
        image: '/images/case4.jpg',
        description: '设计供应链金融解决方案，盘活企业资金链。',
        results: ['授信额度3亿元', '账期优化60天', '上下游带动100家']
    }
];

// 融资租赁行业动态API
const NEWS_API_BASE_URL = 'https://gateway.cfcyun.com/bbs/ainews/list?newsType=99';
let currentPage = 1;
let totalPages = 1;
const pageSize = 5; // 改为每页5

// 加载融资租赁行业动态
async function loadIndustryNews(page = 1) {
    const newsListLarge = document.getElementById('newsListLarge');
    
    // 显示加载状态
    if (page === 1) {
        newsListLarge.innerHTML = `
            <div class="news-loading">
                <div class="loading-spinner"></div>
                <p>正在加载最新动态...</p>
            </div>
        `;
    }
    
    try {
        const response = await fetch(`${NEWS_API_BASE_URL}&pageNum=${page}&pageSize=${pageSize}`);
        const data = await response.json();
        
        if (data.code === 200 && data.rows && data.rows.length > 0) {
            // 按发布时间倒序排序，确保最新的在前面
            const sortedNews = data.rows.sort((a, b) => {
                const dateA = new Date(a.pubDate);
                const dateB = new Date(b.pubDate);
                return dateB - dateA; // 倒序排序，最新的在前面
            });
            
            renderNewsListLarge(sortedNews);
            
            // 更新分页信息
            currentPage = page;
            totalPages = Math.ceil(data.total / pageSize);
            
            // 更新页码信息
            updatePageInfoLarge();
        } else {
            showNewsErrorLarge('暂无动态数据');
        }
    } catch (error) {
        console.error('加载新闻失败:', error);
        showNewsErrorLarge('加载失败，请稍后重试');
    }
}

// 渲染大卡片新闻列表
function renderNewsListLarge(newsData) {
    const newsListLarge = document.getElementById('newsListLarge');   
    const newsHtml = newsData.map(item => {
        const date = formatDate(item.pubDate);
        const title = truncateText(item.title, 50);
        
        return `
            <div class="news-item-large" onclick=openNewsDetail(${item.id})>
                <div class="news-content-large">
                    <div class="news-title-large">${title}</div>
                    <div class=news-date-large">${date}</div>
                </div>
            </div>
        `;
    }).join('');
    
    newsListLarge.innerHTML = newsHtml;
}

// 更新页码信息
function updatePageInfoLarge() {
    const pageInfoLarge = document.getElementById('pageInfoLarge');
    if (pageInfoLarge) {
        pageInfoLarge.textContent = `第${currentPage}页，共${totalPages}页`;
    }
}

// 上一页
function prevNewsPage() {
    if (currentPage > 1) {
        loadIndustryNews(currentPage - 1);
    }
}

// 下一页
function nextNewsPage() {
    if (currentPage < totalPages) {
        loadIndustryNews(currentPage + 1);
    }
}

// 显示错误信息
function showNewsErrorLarge(message) {
    const newsListLarge = document.getElementById('newsListLarge');
    newsListLarge.innerHTML = `
        <div class="news-error">
            <div class="error-icon">📰</div>
            <p>${message}</p>
        </div>
    `;
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diffTime = Math.abs(now - date);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays === 1) {
        return '昨天';
    } else if (diffDays < 7) {
        return `${diffDays}天前`;
    } else if (diffDays < 30) {
        const weeks = Math.floor(diffDays / 7);
        return `${weeks}周前`;
    } else {
        return date.toLocaleDateString('zh-CN', { 
            month: 'short', 
            day: 'numeric' 
        });
    }
}

// 截断文本
function truncateText(text, maxLength) {
    if (!text) return '';
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
}

// 打开新闻详情
function openNewsDetail(newsId) {
    // 这里可以跳转到详情页面或打开弹窗
    window.open(`news-detail.html?id=${newsId}`, '_blank');
}

// 新闻数据
const news = {
    '专精特新资讯': [
        {
            title: '2024年专精特新"小巨人"企业名单发布',
            date: '2024-05-30',
            summary: '工信部发布2024年专精特新"小巨人"企业名单，推动中小企业高质量发展迈上新台阶。'
        },
        {
            title: '国家出台新政支持专精特新企业创新发展',
            date: '2024-05-25',
            summary: '多项政策出台，鼓励专精特新企业加大创新投入，提升核心竞争力。'
        },
        {
            title: '专精特新企业融资新趋势分析',
            date: '2024-05-20',
            summary: '分析专精特新企业在融资渠道、政策支持等方面的新趋势和新机遇。'
        }
    ],
    '政策解读': [
        {
            title: '新版融资租赁监管规定解析',
            date: '2024-03-12',
            summary: '详细解读融资租赁行业最新监管政策。'
        },
        {
            title: '商业保理行业规范指引',
            date: '2024-03-08',
            summary: '解析商业保理行业最新规范要求。'
        }
    ],
    '公司新闻': [
        {
            title: '金顾云荣获"优秀金融服务商"奖',
            date: '2024-03-14',
            summary: '金顾云凭借专业服务能力获得行业认可。'
        },
        {
            title: '金顾云举办2024金融创新论坛',
            date: '2024-03-05',
            summary: '探讨企业金融服务创新与发展。'
        }
    ],
    '专业观点': [
        {
            title: '后疫情时代企业融资策略',
            date: '2024-03-13',
            summary: '专家分析后疫情时代企业融资新思路。'
        },
        {
            title: '数字化时代的金融创新',
            date: '2024-03-07',
            summary: '探讨数字技术对金融服务的革新影响。'
        }
    ]
};

// 数字增长动画
function animateValue(element, start, end, duration, suffix = '') {
    let startTimestamp = null;
    const step = (timestamp) => {
        if (!startTimestamp) startTimestamp = timestamp;
        const progress = Math.min((timestamp - startTimestamp) / duration, 1);
        const current = Math.floor(progress * (end - start) + start);
        
        // 保留原有的span标签内容
        const spanElement = element.querySelector('span');
        if (spanElement) {
            const spanContent = spanElement.outerHTML;
            element.innerHTML = current.toString() + spanContent;
        } else {
            element.textContent = current.toString() + suffix;
        }
        
        if (progress < 1) {
            window.requestAnimationFrame(step);
        }
    };
    window.requestAnimationFrame(step);
}

// 统计数据动画
document.addEventListener('DOMContentLoaded', () => {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const statNumbers = document.querySelectorAll('.stat-number');
                statNumbers.forEach(stat => {
                    // 获取原始HTML内容以保留span标签
                    const originalHTML = stat.innerHTML;
                    const value = parseInt(stat.textContent);
                    
                    // 重置内容，保留span标签
                    stat.innerHTML = '0' + (stat.querySelector('span') ? stat.querySelector('span').outerHTML : '');
                    
                    animateValue(stat, 0, value, 2000);
                });
                observer.unobserve(entry.target);
            }
        });
    });

    const statsSection = document.querySelector('.stats');
    if (statsSection) {
        observer.observe(statsSection);
    }

    // 加载融资租赁行业动态
    if (document.getElementById('newsListLarge')) {
        loadIndustryNews();
    }

    // 案例展示功能 - 只有在存在过滤按钮时才启用
    const casesGrid = document.querySelector('.cases-grid');
    const filterButtons = document.querySelectorAll('.cases-filter .filter-btn');
    
    // 只有在有过滤按钮的页面才执行案例过滤功能
    if (filterButtons.length > 0) {
        function renderCases(filteredCases) {
            casesGrid.innerHTML = filteredCases.map(case_ => `
                <div class="case-card">
                    <div class="case-image">
                        <img src="${case_.image}" alt="${case_.title}">
                    </div>
                    <div class="case-content">
                        <h3>${case_.title}</h3>
                        <p>${case_.description}</p>
                        <div class="case-results">
                            ${case_.results.map(result => `<span class="result-tag">${result}</span>`).join('')}
                        </div>
                        <a href="#" class="learn-more">查看详情 →</a>
                    </div>
                </div>
            `).join('');
        }
        
        // 初始显示所有案例
        renderCases(cases);
        
        // 添加过滤功能
        filterButtons.forEach(button => {
            button.addEventListener('click', () => {
                filterButtons.forEach(btn => btn.classList.remove('active'));
                button.classList.add('active');
                
                const category = button.textContent;
                const filteredCases = category === '全部' ? cases : cases.filter(case_ => case_.category === category);
                renderCases(filteredCases);
            });
        });
    }
    
    // 新闻标签切换功能
    const tabButtons = document.querySelectorAll('.tab-btn');
    const newsGrid = document.querySelector('.news-grid');
    
    function renderNews(category) {
        const newsItems = news[category];
        newsGrid.innerHTML = newsItems.map(item => `
            <div class="news-card">
                <div class="news-date">${item.date}</div>
                <h3>${item.title}</h3>
                <p>${item.summary}</p>
                <a href="#" class="learn-more">阅读全文 →</a>
            </div>
        `).join('');
    }
    
    // 初始显示第一个分类的新闻
    renderNews('专精特新资讯');
    
    // 添加标签切换功能
    tabButtons.forEach(button => {
        button.addEventListener('click', () => {
            tabButtons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
            
            const category = button.textContent;
            renderNews(category);
        });
    });
});

// 表单提交处理
const contactForm = document.getElementById('contactForm');
if (contactForm) {
    contactForm.addEventListener('submit', (e) => {
        e.preventDefault();
        // 这里添加表单提交逻辑
        alert('感谢您的咨询，我们的专业顾问将尽快与您联系！');
        contactForm.reset();
    });
}

// 平滑滚动
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        const target = document.querySelector(this.getAttribute('href'));
        if (target) {
            target.scrollIntoView({
                behavior: 'smooth'
            });
        }
    });
});

// 导航栏滚动效果
let lastScroll = 0;
const nav = document.querySelector('.main-nav');

window.addEventListener('scroll', () => {
    const currentScroll = window.pageYOffset;
    
    if (currentScroll <= 0) {
        nav.classList.remove('scroll-up');
        return;
    }
    
    if (currentScroll > lastScroll && !nav.classList.contains('scroll-down')) {
        nav.classList.remove('scroll-up');
        nav.classList.add('scroll-down');
    } else if (currentScroll < lastScroll && nav.classList.contains('scroll-down')) {
        nav.classList.remove('scroll-down');
        nav.classList.add('scroll-up');
    }
    lastScroll = currentScroll;
}); 

// 移动端交互优化
document.addEventListener('DOMContentLoaded', function() {
    // 检测移动设备
    const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    
    // 移动端触摸优化
    if (isMobile) {
        // 优化触摸滚动
        document.body.style.webkitOverflowScrolling = 'touch';
        
        // 防止双击缩放
        let lastTouchEnd = 0;
        document.addEventListener('touchend', function (event) {
            const now = (new Date()).getTime();
            if (now - lastTouchEnd <= 300) {
                event.preventDefault();
            }
            lastTouchEnd = now;
        }, false);
        
        // 优化按钮触摸反馈
        const buttons = document.querySelectorAll('.btn, .btn-outline, .btn-partner, .btn-financing');
        buttons.forEach(button => {
            button.addEventListener('touchstart', function() {
                this.style.transform = 'scale(0.98)';
            });
            
            button.addEventListener('touchend', function() {
                this.style.transform = 'scale(1)';
            });
        });
    }
    
    // 移动端导航优化
    const navMenu = document.querySelector('.nav-menu');
    if (navMenu) {
        // 移动端菜单项点击优化
        const navItems = navMenu.querySelectorAll('a');
        navItems.forEach(item => {
            item.addEventListener('click', function(e) {
                // 在移动端点击导航项后添加视觉反馈
                if (isMobile) {
                    this.style.backgroundColor = 'rgba(222, 41, 16, 0.1)';
                    setTimeout(() => {
                        this.style.backgroundColor = '';
                    }, 200);
                }
            });
        });
    }
    
    // 移动端卡片交互优化
    const cards = document.querySelectorAll('.finance-card, .solution-card, .case-card, .product-card');
    cards.forEach(card => {
        if (isMobile) {
            card.addEventListener('touchstart', function() {
                this.style.transform = 'scale(0.98)';
            });
            
            card.addEventListener('touchend', function() {
                this.style.transform = 'scale(1)';
            });
        }
    });
    
    // 移动端表单优化
    const formInputs = document.querySelectorAll('input, textarea');
    formInputs.forEach(input => {
        // 防止iOS缩放
        input.addEventListener('focus', function() {
            if (isMobile) {
                this.style.fontSize = '16px';
            }
        });
        
        // 优化移动端输入体验
        input.addEventListener('blur', function() {
            if (isMobile) {
                this.style.fontSize = '';
            }
        });
    });
    
    // 移动端滚动优化
    let ticking = false;
    function updateScroll() {
        if (!ticking) {
            requestAnimationFrame(function() {
                // 滚动时的性能优化
                ticking = false;
            });
            ticking = true;
        }
    }
    
    window.addEventListener('scroll', updateScroll, { passive: true });
    
    // 移动端图片懒加载优化
    const images = document.querySelectorAll('img[data-src]');
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.classList.remove('lazy');
                    imageObserver.unobserve(img);
                }
            });
        });
        
        images.forEach(img => imageObserver.observe(img));
    }
    
    // 移动端性能监控
    if (isMobile) {
        // 监控页面加载性能
        window.addEventListener('load', function() {
            if ('performance' in window) {
                const perfData = performance.getEntriesByType('navigation')[0];
                console.log('页面加载时间:', perfData.loadEventEnd - perfData.loadEventStart, 'ms');
            }
        });
    }
});

// 移动端手势支持
function addSwipeSupport(element, onSwipeLeft, onSwipeRight) {
    let startX = 0;
    let startY = 0;
    let endX = 0;
    let endY = 0;
    
    element.addEventListener('touchstart', function(e) {
        startX = e.touches[0].clientX;
        startY = e.touches[0].clientY;
    });
    
    element.addEventListener('touchend', function(e) {
        endX = e.changedTouches[0].clientX;
        endY = e.changedTouches[0].clientY;
        
        const diffX = startX - endX;
        const diffY = startY - endY;
        
        // 确保是水平滑动
        if (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 50) {
            if (diffX > 0 && onSwipeLeft) {
                onSwipeLeft();
            } else if (diffX < 0 && onSwipeRight) {
                onSwipeRight();
            }
        }
    });
}

// 移动端轮播图手势支持
const carouselContainer = document.querySelector('.carousel-container');
if (carouselContainer) {
    addSwipeSupport(
        carouselContainer,
        () => next(), // 左滑下一张
        () => prev()  // 右滑上一张
    );
}

// 移动端返回顶部功能
function addBackToTop() {
    const backToTopBtn = document.createElement('button');
    backToTopBtn.innerHTML = '<i class="fas fa-arrow-up"></i>';
    backToTopBtn.className = 'back-to-top';
    backToTopBtn.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background: var(--primary-color);
        color: white;
        border: none;
        cursor: pointer;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s ease;
        z-index: 1000;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px;
    `;
    
    document.body.appendChild(backToTopBtn);
    
    window.addEventListener('scroll', function() {
        if (window.pageYOffset > 300) {
            backToTopBtn.style.opacity = '1';
            backToTopBtn.style.visibility = 'visible';
        } else {
            backToTopBtn.style.opacity = '0';
            backToTopBtn.style.visibility = 'hidden';
        }
    });
    
    backToTopBtn.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
}

// 初始化返回顶部功能
addBackToTop(); 

// 移动端导航栏功能 - 注释掉，避免与load-nav.js冲突
/*
document.addEventListener('DOMContentLoaded', function() {
    // 创建汉堡菜单按钮
    function createMobileMenuToggle() {
        const nav = document.querySelector('.main-nav');
        if (!nav) return;
        
        const mobileToggle = document.createElement('button');
        mobileToggle.className = 'mobile-menu-toggle';
        mobileToggle.innerHTML = '<span></span><span></span><span></span>';
        mobileToggle.setAttribute('aria-label', '打开菜单');
        
        // 插入到导航栏中
        const navButtons = nav.querySelector('.nav-buttons');
        if (navButtons) {
            navButtons.parentNode.insertBefore(mobileToggle, navButtons);
        }
        
        return mobileToggle;
    }
    
    // 创建移动端导航菜单
    function createMobileNav() {
        const mobileNav = document.createElement('div');
        mobileNav.className = 'mobile-nav';
        
        // 创建导航内容区域
        const mobileNavContent = document.createElement('div');
        mobileNavContent.className = 'mobile-nav-content';
        
        // 创建导航头部
        const mobileNavHeader = document.createElement('div');
        mobileNavHeader.className = 'mobile-nav-header';
        
        // 添加logo
        const logo = document.querySelector('.logo img');
        const mobileNavLogo = document.createElement('div');
        mobileNavLogo.className = 'mobile-nav-logo';
        mobileNavLogo.innerHTML = `
            <img src="${logo ? logo.src : ''}" alt="金顾云logo">
            <div class="mobile-nav-logo-text">金顾云</div>
        `;
        
        // 添加关闭按钮
        const mobileNavClose = document.createElement('button');
        mobileNavClose.className = 'mobile-nav-close';
        mobileNavClose.innerHTML = '×';
        mobileNavClose.setAttribute('aria-label', '关闭菜单');
        
        mobileNavHeader.appendChild(mobileNavLogo);
        mobileNavHeader.appendChild(mobileNavClose);
        
        // 创建导航菜单列表
        const mobileNavList = document.createElement('ul');
        
        // 定义正确的导航结构
        const navStructure = [
            { text: '首页', url: 'index.html', active: window.location.pathname.includes('index.html') || window.location.pathname === '/' },
            { 
                text: '融顾服务', 
                hasDropdown: true,
                children: [
                    { text: '融资外包', url: 'finance-outsourcing-center.html' },
                    { text: '常顾服务', url: 'consultant.html' }
                ]
            },
            { 
                text: '金顾云学院', 
                hasDropdown: true,
                children: [
                    { text: '学院简介', url: 'finance-course.html' },
                    { text: '学院课程', url: 'academy-courses.html' }
                ]
            },
            { text: '金顾云俱乐部', url: 'club.html' },
            { text: '金顾云公益', url: 'charity.html' },
            { text: '金顾云党建', url: 'party.html' },
            { text: '合伙人加盟', url: 'partner.html' },
            { text: '关于金顾云', url: 'about.html' }
        ];
        
        // 生成导航菜单HTML
        navStructure.forEach(item => {
            const li = document.createElement('li');
            
            if (item.hasDropdown) {
                // 有子菜单的项目
                const link = document.createElement('a');
                link.href = '#';
                link.textContent = item.text;
                link.className = 'has-dropdown';
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    this.classList.toggle('active');
                    const dropdown = this.nextElementSibling;
                    dropdown.classList.toggle('active');
                });
                
                const dropdown = document.createElement('div');
                dropdown.className = 'mobile-dropdown';
                
                item.children.forEach(child => {
                    const childLink = document.createElement('a');
                    childLink.href = child.url;
                    childLink.textContent = child.text;
                    dropdown.appendChild(childLink);
                });
                
                li.appendChild(link);
                li.appendChild(dropdown);
            } else {
                // 普通菜单项
                const link = document.createElement('a');
                link.href = item.url;
                link.textContent = item.text;
                if (item.active) {
                    link.classList.add('active');
                }
                li.appendChild(link);
            }
            
            mobileNavList.appendChild(li);
        });
        
        // 组装导航结构
        mobileNavContent.appendChild(mobileNavHeader);
        mobileNavContent.appendChild(mobileNavList);
        mobileNav.appendChild(mobileNavContent);
        
        document.body.appendChild(mobileNav);
        return mobileNav;
    }
    
    // 初始化移动端导航
    function initMobileNav() {
        const mobileToggle = createMobileMenuToggle();
        const mobileNav = createMobileNav();
        
        if (!mobileToggle || !mobileNav) return;
        
        // 切换菜单状态
        mobileToggle.addEventListener('click', function() {
            toggleMobileNav(mobileNav, mobileToggle, true);
        });
        
        // 关闭按钮事件
        const closeBtn = mobileNav.querySelector('.mobile-nav-close');
        if (closeBtn) {
            closeBtn.addEventListener('click', function() {
                toggleMobileNav(mobileNav, mobileToggle, false);
            });
        }
        
        // 点击菜单项关闭菜单（除了有子菜单的）
        const mobileLinks = mobileNav.querySelectorAll('a:not(.has-dropdown)');
        mobileLinks.forEach(link => {
            link.addEventListener('click', function() {
                toggleMobileNav(mobileNav, mobileToggle, false);
            });
        });
        
        // 点击背景关闭菜单
        mobileNav.addEventListener('click', function(e) {
            if (e.target === mobileNav) {
                toggleMobileNav(mobileNav, mobileToggle, false);
            }
        });
        
        // ESC键关闭菜单
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && mobileNav.classList.contains('active')) {
                toggleMobileNav(mobileNav, mobileToggle, false);
            }
        });
        
        // 窗口大小变化时处理
        window.addEventListener('resize', function() {
            if (window.innerWidth > 768) {
                toggleMobileNav(mobileNav, mobileToggle, false);
            }
        });
    }
    
    // 切换移动端导航状态
    function toggleMobileNav(mobileNav, mobileToggle, show) {
        if (show) {
            mobileNav.classList.add('active');
            mobileToggle.classList.add('active');
            mobileToggle.setAttribute('aria-label', '关闭菜单');
            document.body.style.overflow = 'hidden';
        } else {
            mobileNav.classList.remove('active');
            mobileToggle.classList.remove('active');
            mobileToggle.setAttribute('aria-label', '打开菜单');
            document.body.style.overflow = '';
            
            // 关闭所有子菜单
            const dropdowns = mobileNav.querySelectorAll('.mobile-dropdown.active');
            dropdowns.forEach(dropdown => {
                dropdown.classList.remove('active');
            });
            
            const activeLinks = mobileNav.querySelectorAll('a.has-dropdown.active');
            activeLinks.forEach(link => {
                link.classList.remove('active');
            });
        }
    }
    
    // 初始化移动端导航
    initMobileNav();
});
*/ 